# Name: JoinMunicGrid.py - MCBS 10/18/2014
# Description: Joins munic geocodigo from IBGE to grid and saves table

# import system module
import arcpy
from arcpy import env
#from arcpy.sa import *


# Set workspace environment:
#env.workspace = "CanasatData.gdb"
env.workspace = "C:\Users\Marcelo\Documents\Sugarcane\Offline Data\MunicBasedData\CanasatData.gdb"
env.overwriteOutput = True
#arcpy.CheckOutExtension("Spatial")

# Folder to store tables:
PathForTables = "C:\Users\Marcelo\Documents\Sugarcane\Offline Data\MunicBasedData\Tables"

# Input grid:
GridName      = "G1kmMiR"
# Output grids name:
OutName       = "G1kmMiRMunic"

JoinClass       = "Municipalities" 
OutputFeature   = OutName
fieldmappings   = arcpy.FieldMappings()
fieldmappings.addTable(GridName)
fieldmappings.addTable(JoinClass)
x = fieldmappings.findFieldMapIndex("geocodigo")
fieldmappings.removeFieldMap(x)
x = fieldmappings.findFieldMapIndex("nomeabrev")
fieldmappings.removeFieldMap(x)
x = fieldmappings.findFieldMapIndex("id_municip")
fieldmappings.removeFieldMap(x)
x = fieldmappings.findFieldMapIndex("nome")
fieldmappings.removeFieldMap(x)
x = fieldmappings.findFieldMapIndex("geometriaa")
fieldmappings.removeFieldMap(x)
arcpy.SpatialJoin_analysis(GridName, JoinClass, OutputFeature,
						   "JOIN_ONE_TO_MANY", "KEEP_ALL", fieldmappings,
						   "COMPLETELY_WITHIN", "", "")
print "Joining attributes from " + JoinClass + " to grid."
print "New Grid file containing attributes created: " + OutputFeature
print " "
# Save .dbf tables in specified folder
TableName    = OutputFeature + ".dbf"
arcpy.TableToTable_conversion(OutputFeature, PathForTables, TableName)


